<template>
	<view class="container">
		<view class="form-section">
			<!-- 页面标题 -->
			<view class="page-title">规格定价</view>
			
			<!-- 规格选择区域 -->
			<view class="specs-selection">
				<!-- 整体长度 -->
				<view class="spec-group">
					<view class="spec-header">
						<text class="spec-title">整体长度</text>
						<text class="all-select" @tap="toggleSelectAll('lengthList')">{{isAllSelected('lengthList') ? '取消全选' : '全选'}}</text>
					</view>
					<view class="spec-items">
						<view 
							v-for="(item, index) in productSpecs.lengthList" 
							:key="'length'+index"
							:class="['spec-item', isSelected('lengthList', item) ? 'selected' : '']"
							@tap="toggleSpec('lengthList', item)"
						>
							{{item}}
						</view>
					</view>
				</view>
				
				<!-- 佩戴直径 -->
				<view class="spec-group">
					<view class="spec-header">
						<text class="spec-title">佩戴直径</text>
						<text class="all-select" @tap="toggleSelectAll('diameterList')">{{isAllSelected('diameterList') ? '取消全选' : '全选'}}</text>
					</view>
					<view class="spec-items">
						<view 
							v-for="(item, index) in productSpecs.diameterList" 
							:key="'diameter'+index"
							:class="['spec-item', isSelected('diameterList', item) ? 'selected' : '']"
							@tap="toggleSpec('diameterList', item)"
						>
							{{item}}
						</view>
					</view>
				</view>
				
				<!-- 珍珠颜色 -->
				<view class="spec-group">
					<view class="spec-header">
						<text class="spec-title">珍珠颜色</text>
						<text class="all-select" @tap="toggleSelectAll('pearlColorList')">{{isAllSelected('pearlColorList') ? '取消全选' : '全选'}}</text>
					</view>
					<view class="spec-items">
						<view 
							v-for="(item, index) in productSpecs.pearlColorList" 
							:key="'color'+index"
							:class="['spec-item', isSelected('pearlColorList', item) ? 'selected' : '']"
							@tap="toggleSpec('pearlColorList', item)"
						>
							{{item}}
						</view>
					</view>
				</view>
				
				<!-- 珍珠尺寸 -->
				<view class="spec-group">
					<view class="spec-header">
						<text class="spec-title">珍珠尺寸</text>
						<text class="all-select" @tap="toggleSelectAll('pearlSizeList')">{{isAllSelected('pearlSizeList') ? '取消全选' : '全选'}}</text>
					</view>
					<view class="spec-items">
						<view 
							v-for="(item, index) in productSpecs.pearlSizeList" 
							:key="'size'+index"
							:class="['spec-item', isSelected('pearlSizeList', item) ? 'selected' : '']"
							@tap="toggleSpec('pearlSizeList', item)"
						>
							{{item}}
						</view>
					</view>
				</view>
			</view>
			
			<!-- SKU列表 - 编号、标价和售价 -->
			<view class="sku-list">
				<view class="sku-header">
					<view class="sku-header-item">规格</view>
					<view class="sku-header-item">编号</view>
					<view class="sku-header-item">标价</view>
					<view class="sku-header-item">售价</view>
				</view>
				
				<view class="sku-item" v-for="(sku, index) in generatedSkus" :key="index">
					<view class="sku-spec">
						<view v-if="sku.length">长度: {{sku.length}}</view>
						<view v-if="sku.diameter">直径: {{sku.diameter}}</view>
						<view v-if="sku.pearlColor">颜色: {{sku.pearlColor}}</view>
						<view v-if="sku.pearlSize">尺寸: {{sku.pearlSize}}</view>
					</view>
					<view class="sku-code">
						<text>{{sku.skuCode || '保存后自动生成'}}</text>
					</view>
					<view class="sku-price">
						<input type="number" v-model="sku.listPrice" placeholder="标价" />
					</view>
					<view class="sku-price">
						<input type="number" v-model="sku.salePrice" placeholder="售价" />
					</view>
				</view>
				
				<!-- 批量设置价格 -->
				<view class="batch-price-setting" v-if="generatedSkus.length > 0">
					<view class="batch-title">批量设置</view>
					<view class="batch-inputs">
						<view class="batch-input-group">
							<input type="number" v-model="batchListPrice" placeholder="标价" />
							<button class="batch-btn" @tap="setBatchListPrice">应用</button>
						</view>
						<view class="batch-input-group">
							<input type="number" v-model="batchSalePrice" placeholder="售价" />
							<button class="batch-btn" @tap="setBatchSalePrice">应用</button>
						</view>
					</view>
				</view>
			</view>
		</view>
		
		<!-- 底部按钮 -->
		<view class="bottom-bar">
			<view class="bottom-btn-container">
				<button class="back-btn" @tap="goBack">返回</button>
				<button class="save-btn" @tap="saveSkus">完成</button>
			</view>
		</view>
	</view>
</template>

<script>
	import { productApi } from '../../api/index.js';
	
	export default {
		data() {
			return {
				productId: '',
				productInfo: {},
				productSpecs: {},
				selectedSpecs: {
					lengthList: [],
					diameterList: [],
					pearlSizeList: [],
					pearlColorList: []
				},
				generatedSkus: [],
				
				// 批量设置价格
				batchListPrice: '',
				batchSalePrice: '',
				
				isLoading: false,
				
				// 商品类别代号映射
				categoryCodeMap: {
					'耳饰': 'ES',
					'项链': 'XL',
					'手链': 'SL',
					'戒指': 'JZ',
					'胸针': 'XZ',
					'其他': 'QT'
				},
			}
		},
		onLoad(options) {
			// 处理从URL参数传递过来的数据
			try {
				console.log('接收到的数据:', options.productData);

				const data = JSON.parse(decodeURIComponent(options.productData));
				// 保存完整的数据
				this.productInfo = data.productData || {};
				this.productId = data.productData.id;
				console.log('接收到的商品数据:', this.productInfo);
				console.log('现有SKU数据:', this.productInfo.skus);
				this.initProductSpecs(data);
			} catch (error) {
				console.error('解析商品数据失败', error);
				uni.showToast({
					title: '解析商品数据失败', 
					icon: 'none'
				});
			}
			
		},
		methods: {
			// 初始化产品规格
			initProductSpecs(data) {
				console.log('初始化规格数据...');
				console.log('接收到的规格数据:', data.selectedInfo);
				
				// 初始化商品规格数据
				this.productSpecs = {
					lengthList: Array.isArray(data.selectedInfo.lengthList) ? [...data.selectedInfo.lengthList] : [],
					diameterList: Array.isArray(data.selectedInfo.diameterList) ? [...data.selectedInfo.diameterList] : [],
					pearlSizeList: Array.isArray(data.selectedInfo.pearlSizeList) ? [...data.selectedInfo.pearlSizeList] : [],
					pearlColorList: Array.isArray(data.selectedInfo.pearlColorList) ? [...data.selectedInfo.pearlColorList] : []
				};
				
				console.log('初始化后的productSpecs:', this.productSpecs);
				
				// 初始时全部选中（使用深拷贝避免引用问题）
				this.selectedSpecs = {
					lengthList: [...this.productSpecs.lengthList],
					diameterList: [...this.productSpecs.diameterList],
					pearlSizeList: [...this.productSpecs.pearlSizeList],
					pearlColorList: [...this.productSpecs.pearlColorList]
				};
				
				console.log('初始化后的selectedSpecs:', this.selectedSpecs);
				
				// 生成SKU组合
				this.generateSkus();
			},
			
			// 切换规格选择状态
			toggleSpec(type, value) {
				const index = this.selectedSpecs[type].indexOf(value);
				if (index === -1) {
					// 添加选择
					this.selectedSpecs[type].push(value);
				} else {
					// 移除选择
					this.selectedSpecs[type].splice(index, 1);
				}
				
				// 重新生成SKU
				this.generateSkus();
			},
			
			// 检查规格是否被选中
			isSelected(type, value) {
				// 确保selectedSpecs[type]是一个数组
				if (!Array.isArray(this.selectedSpecs[type])) {
					console.error(`selectedSpecs.${type} is not an array:`, this.selectedSpecs[type]);
					return false;
				}
				return this.selectedSpecs[type].includes(value);
			},
			
			// 全选/取消全选
			toggleSelectAll(type) {
				// 确保selectedSpecs和productSpecs是正确初始化的
				if (!this.selectedSpecs || !this.productSpecs) {
					console.error('selectedSpecs or productSpecs is not properly initialized');
					return;
				}
				
				// 确保数组类型正确
				if (!Array.isArray(this.selectedSpecs[type])) {
					this.selectedSpecs[type] = [];
				}
				
				if (!Array.isArray(this.productSpecs[type])) {
					this.productSpecs[type] = [];
				}
				
				if (this.isAllSelected(type)) {
					// 如果全部选中，则取消全选
					this.selectedSpecs[type] = [];
				} else {
					// 否则，全选
					this.selectedSpecs[type] = [...this.productSpecs[type]];
				}
				
				console.log(`${type} 选择状态更新:`, this.selectedSpecs[type]);
				
				// 重新生成SKU
				this.generateSkus();
			},
			
			// 检查是否全选
			isAllSelected(type) {
				// 确保数组类型正确
				if (!Array.isArray(this.selectedSpecs[type]) || !Array.isArray(this.productSpecs[type])) {
					console.error(`selectedSpecs.${type} or productSpecs.${type} is not an array`);
					return false;
				}
				
				// 如果没有可选项或没有选择，返回false
				if (this.productSpecs[type].length === 0) {
					return false;
				}
				
				return this.selectedSpecs[type].length === this.productSpecs[type].length;
			},
			
			// 获取商品类别代号
			getCategoryCode() {
				const category = this.productInfo.category || '';
				// 查找类别代号，如果没有对应的则使用"其他"
				for (const key in this.categoryCodeMap) {
					if (category.includes(key)) {
						return this.categoryCodeMap[key];
					}
				}
				return 'QT'; // 默认为"其他"
			},
			
			// 生成SKU组合
			generateSkus() {
				// 准备各维度的值
				const dimensions = [
					this.selectedSpecs.lengthList.length > 0 ? this.selectedSpecs.lengthList : [''],
					this.selectedSpecs.diameterList.length > 0 ? this.selectedSpecs.diameterList : [''],
					this.selectedSpecs.pearlColorList.length > 0 ? this.selectedSpecs.pearlColorList : [''],
					this.selectedSpecs.pearlSizeList.length > 0 ? this.selectedSpecs.pearlSizeList : ['']
				];
				
				console.log('生成SKU的维度:', dimensions);
				
				// 存储现有的SKU数据，用于后面匹配
				const existingSkus = this.productInfo.skus || [];
				console.log('现有SKU数据用于匹配:', existingSkus);
				
				// 生成所有组合
				this.generatedSkus = [];
				this.generateCombinations(dimensions, 0, {}, this.generatedSkus);
				
				// 过滤掉空SKU（所有规格都为空的组合）
				this.generatedSkus = this.generatedSkus.filter(sku => {
					return sku.length || sku.diameter || sku.pearlColor || sku.pearlSize;
				});
				
				// 如果没有生成任何SKU，显示一个空白SKU
				if (this.generatedSkus.length === 0) {
				}
				
				// 对于每个生成的SKU，检查是否已存在，如果存在则保留其价格和SKU编码
				let matchCount = 0;
				this.generatedSkus.forEach(newSku => {
					// 尝试在现有SKU中找到匹配项
					const existingSku = existingSkus.find(oldSku => 
						oldSku.length === newSku.length && 
						oldSku.diameter === newSku.diameter && 
						oldSku.pearlColor === newSku.pearlColor && 
						oldSku.pearlSize === newSku.pearlSize
					);
					
					// 如果找到匹配的SKU，保留其价格和SKU编码
					if (existingSku) {
						matchCount++;
						newSku.listPrice = existingSku.listPrice || '';
						newSku.salePrice = existingSku.salePrice || '';
						newSku.skuCode = existingSku.skuCode || '';
						// 保留其他可能的字段
						newSku.id = existingSku.id;
						newSku.stock = existingSku.stock;
						newSku.barcode = existingSku.barcode;
					} else {
						// 新SKU，清空编号
						newSku.skuCode = '';
					}
				});
				
				console.log(`生成了 ${this.generatedSkus.length} 个SKU，其中匹配到 ${matchCount} 个现有SKU`);
				console.log('生成的SKU数据:', this.generatedSkus);
			},
			
			// 递归生成所有组合
			generateCombinations(dimensions, level, current, result) {
				if (level === dimensions.length) {
					// 到达最后一个维度，添加当前组合
					result.push({
						length: current['length'] || '',
						diameter: current['diameter'] || '',
						pearlColor: current['pearlColor'] || '',
						pearlSize: current['pearlSize'] || '',
						listPrice: '',  // 标价
						salePrice: ''   // 售价
					});
					return;
				}
				
				// 当前维度的所有可能值
				const dimValues = dimensions[level];
				
				// 遍历当前维度，递归生成组合
				for (const value of dimValues) {
					const newCurrent = { ...current };
					
					// 根据level设置相应的属性
					if (level === 0 && value) newCurrent['length'] = value;
					if (level === 1 && value) newCurrent['diameter'] = value;
					if (level === 2 && value) newCurrent['pearlColor'] = value;
					if (level === 3 && value) newCurrent['pearlSize'] = value;
					
					// 递归下一级
					this.generateCombinations(dimensions, level + 1, newCurrent, result);
				}
			},
			
			// 批量设置标价
			setBatchListPrice() {
				if (!this.batchListPrice) {
					uni.showToast({
						title: '请输入批量标价',
						icon: 'none'
					});
					return;
				}
				
				// 将批量标价应用到所有SKU
				this.generatedSkus.forEach(sku => {
					sku.listPrice = this.batchListPrice;
				});
				
				uni.showToast({
					title: '批量设置标价成功',
					icon: 'success'
				});
			},
			
			// 批量设置售价
			setBatchSalePrice() {
				if (!this.batchSalePrice) {
					uni.showToast({
						title: '请输入批量售价',
						icon: 'none'
					});
					return;
				}
				
				// 将批量售价应用到所有SKU
				this.generatedSkus.forEach(sku => {
					sku.salePrice = this.batchSalePrice;
				});
				
				uni.showToast({
					title: '批量设置售价成功',
					icon: 'success'
				});
			},
			
			// 验证SKU数据
			validateSkus() {
				// 检查是否有SKU
				/* 暂时不检查
				if (this.generatedSkus.length === 0) {
					uni.showToast({
						title: '请至少选择一个规格',
						icon: 'none'
					});
					return false;
				}
				*/
				
				// 检查每个SKU的价格是否已设置
				for (const sku of this.generatedSkus) {
					if (!sku.listPrice || !sku.salePrice) {
						uni.showToast({
							title: '请为所有规格设置价格',
							icon: 'none'
						});
						return false;
					}
				}
				
				return true;
			},
			
			// 保存SKU到产品
			async saveSkus() {
				if (!this.validateSkus()) return;
				
				try {
					uni.showLoading({ title: '保存中...' });
					this.isLoading = true;
					
					// 计算需要新生成SKU码的数量
					const skusNeedingCodes = this.generatedSkus.filter(sku => !sku.skuCode).length;
					
					// 只有当有需要新生成的SKU码时才请求服务器
					if (skusNeedingCodes > 0) {
							
						// 获取日期或使用当前日期
						let dateStr;
						const date = new Date(this.productInfo.date);
						const year = date.getFullYear().toString().slice(-2);
						const month = (date.getMonth() + 1).toString().padStart(2, '0');
						const day = date.getDate().toString().padStart(2, '0');
						dateStr = year + month + day;
						
						// 获取商品类别代号
						const categoryCode = this.getCategoryCode();
						
						// 从服务器获取SKU编号
						const response = await productApi.generateSkuCodes({
							categoryCode,
							dateStr,
							skuCount: skusNeedingCodes,
							productId: this.productId || null
						});
						
						// 确保响应格式正确
						const skuCodes = response && response.data ? response.data : [];
						
						// 将新生成的SKU码分配给需要的SKU
						let codeIndex = 0;
						this.generatedSkus.forEach(sku => {
							if (!sku.skuCode && skuCodes.length > codeIndex) {
								sku.skuCode = skuCodes[codeIndex++];
							}
						});
					}

					// 将生成的SKU数据合并到产品信息中
					this.productInfo.skus = this.generatedSkus;
					
					// 保存到后端
					if (this.productId) {
						// 更新现有产品
						console.log('更新后的产品信息:', this.productInfo);
						await productApi.updateProduct(this.productId, this.productInfo);
						uni.showToast({
							title: '更新成功',
							icon: 'success'
						});
					} else {
						// 创建新产品
						const result = await productApi.createProduct(this.productInfo);
						this.productId = result.id;
						uni.showToast({
							title: '创建成功',
							icon: 'success'
						});
					}
					
					uni.hideLoading();
					this.isLoading = false;
					
					// 延迟1秒返回列表页
					setTimeout(() => {
						uni.switchTab({
							url: '/pages/list/list'
						});
					}, 1000);
				} catch (error) {
					console.error('保存SKU失败', error);
					uni.hideLoading();
					this.isLoading = false;
					
					uni.showToast({
						title: '保存失败，请重试',
						icon: 'none'
					});
				}
			},
			
			// 返回上一页
			goBack() {
				uni.navigateBack({
					delta: 1
				});
			}
		}
	}
</script>

<style>
	.container {
		min-height: 100vh;
		background-color: #f5f5f5;
		padding-bottom: 120rpx;
	}
	
	.form-section {
		background-color: #fff;
		padding: 20rpx;
	}
	
	.page-title {
		font-size: 36rpx;
		color: #333;
		font-weight: bold;
		text-align: center;
		margin: 30rpx 0;
	}
	
	/* 规格选择样式 */
	.specs-selection {
		margin-bottom: 40rpx;
	}
	
	.spec-group {
		margin-bottom: 30rpx;
	}
	
	.spec-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 20rpx;
	}
	
	.spec-title {
		font-size: 30rpx;
		color: #333;
		font-weight: bold;
	}
	
	.all-select {
		font-size: 26rpx;
		color: #F3B250;
	}
	
	.spec-items {
		display: flex;
		flex-wrap: wrap;
		gap: 16rpx;
	}
	
	.spec-item {
		padding: 16rpx 24rpx;
		background-color: #f5f5f5;
		border-radius: 8rpx;
		font-size: 28rpx;
		color: #333;
	}
	
	.spec-item.selected {
		background-color: rgba(243, 178, 80, 0.1);
		color: #F3B250;
		border: 1px solid #F3B250;
	}
	
	/* SKU列表样式 */
	.sku-list {
		background-color: #fff;
		border-radius: 16rpx;
		padding: 20rpx;
		margin-bottom: 40rpx;
	}
	
	.sku-header {
		display: flex;
		border-bottom: 1px solid #EEE;
		padding-bottom: 20rpx;
		margin-bottom: 10rpx;
	}
	
	.sku-header-item {
		flex: 1;
		text-align: center;
		font-size: 28rpx;
		color: #333;
		font-weight: bold;
	}
	
	.sku-count {
		font-size: 26rpx;
		color: #333;
		margin-bottom: 20rpx;
	}
	
	.sku-item {
		display: flex;
		padding: 20rpx 0;
		border-bottom: 1px solid #F5F5F5;
	}
	
	.sku-spec {
		flex: 1;
		font-size: 26rpx;
		color: #333;
	}
	
	.sku-code {
		flex: 1;
		display: flex;
		justify-content: center;
		align-items: center;
		font-size: 24rpx;
		color: #333;
	}
	
	.sku-price {
		flex: 1;
		display: flex;
		justify-content: center;
		align-items: center;
	}
	
	.sku-price input {
		width: 85%;
		height: 70rpx;
		background-color: #F5F5F5;
		border-radius: 8rpx;
		padding: 0 20rpx;
		font-size: 26rpx;
		text-align: center;
	}
	
	/* 批量设置价格 */
	.batch-price-setting {
		margin-top: 40rpx;
		border-top: 1px solid #EEE;
		padding-top: 20rpx;
	}
	
	.batch-title {
		font-size: 28rpx;
		color: #333;
		font-weight: bold;
		margin-bottom: 20rpx;
	}
	
	.batch-inputs {
		display: flex;
		justify-content: space-between;
		gap: 20rpx;
	}
	
	.batch-input-group {
		flex: 1;
		display: flex;
		align-items: center;
	}
	
	.batch-input-group input {
		flex: 1;
		height: 80rpx;
		background-color: #F5F5F5;
		border-radius: 8rpx;
		padding: 0 20rpx;
		font-size: 26rpx;
	}
	
	.batch-btn {
		width: 140rpx;
		height: 80rpx;
		line-height: 80rpx;
		background-color: #F3B250;
		color: #fff;
		font-size: 26rpx;
		border-radius: 8rpx;
		margin-left: 20rpx;
	}
	
	/* 底部按钮 */
	.bottom-bar {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		height: 90rpx;
		background-color: #fff;
		display: flex;
		justify-content: center;
		align-items: center;
		padding: 0 30rpx;
		box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
	}
	
	.bottom-btn-container {
		display: flex;
		height: 90rpx;
		background-color: #fff;
		align-items: center;
		justify-content: center;
		padding: 0 10rpx;
	}
	
	.back-btn {
		flex: 0 0 auto;
		width: 200rpx;
		height: 50rpx;
		line-height: 50rpx;
		text-align: center;
		background-color: #fff;
		color: #282828;
		border-radius: 0rpx;
		border: 4rpx solid #dcc8a5;
		margin: 0 15rpx;
		font-size: 28rpx;
		font-family: Regular;
		padding: 0;
	}
	
	.back-btn::after {
		border: none;
	}
	
	.save-btn {
		flex: 0 0 auto;
		width: 200rpx;
		height: 50rpx;
		line-height: 50rpx;
		text-align: center;
		background-color: #282828;
		color: #fff;
		border-radius: 0rpx;
		border: 4rpx solid #dcc8a5;
		margin: 0 15rpx;
		font-size: 28rpx;
		font-family: Regular;
		padding: 0;
	}
	
	.save-btn::after {
		border: none;
	}
</style> 